<template>
  <el-form ref="formRef" :model="formData" :rules="rules" size="large">
    <el-form-item prop="phone">
      <el-input
        v-model="formData.phone"
        placeholder="请输入手机号"
        prefix-icon="Cellphone"
      >
        <template #prepend>+86</template>
      </el-input>
    </el-form-item>
    <el-form-item prop="code">
      <div class="send-code">
        <el-input
          v-model="formData.code"
          placeholder="请输入验证码"
          prefix-icon="Lock"
          @keyup.enter="handleLogin"
        />
        <el-button :disabled="countdown > 0" @click="sendCode">
          {{ countdown > 0 ? `${countdown} s` : '发送验证码' }}
        </el-button>
      </div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" style="width: 100%" @click="handleLogin"
        >登录</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { isPhone } from '@/utils/regexp'
import useForm from '@/hooks/useForm'
import useUserStore from '@/store/modules/user'

const { formData, formRef } = useForm({
  phone: '',
  code: '',
})
const { login } = useUserStore()

const countdown = ref(0)
const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!isPhone(value)) {
          callback(new Error('手机号格式不正确'))
        } else {
          callback()
        }
      },
    },
  ],
  code: [{ required: true, message: '请填写验证码', trigger: 'blur' }],
}
let timer = null

onBeforeUnmount(() => timer && clearInterval(timer))

async function handleLogin() {
  await formRef.value.validate()
  const formDataVal = formData.vlaue
  login({
    username: formDataVal.phone,
    password: formDataVal.code,
  })
}

function sendCode() {
  if (!isPhone(formData.value.phone)) {
    return ElMessage.warning('手机号格式不正确')
  }
  if (countdown.value > 0) return

  countdown.value = 60
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}
</script>

<style lang="scss" scoped>
.send-code {
  width: 100%;
  display: flex;

  .el-button {
    margin-left: $space-small;
  }
}
</style>
